<template>
<div class="article-container">
  <head>
    <meta name="referrer" content="no-referrer">
  </head>
  <!-- 导航栏 -->
  <van-nav-bar class="page-nav-bar">
    <template slot="left" v-if="authVisible">
      <van-icon name="arrow-left" @click="onClickLeft"/>
      <van-image class="avatar" round fit="cover" :src="news.aut_photo" width="35" height="35"/>
      <span class="autname">{{news.aut_name}}</span>
      <van-button
        v-if="news.isFollowed"
        class="follow-btn"
        type="info"
        color="#3296fa"
        round
        size="small"
        icon="plus"
        @click="onFollow"
      >关注</van-button>
      <van-button v-else class="follow-btn" round size="small" @click="onFollow">已关注</van-button>
    </template>
    <span slot="right">
      <van-icon name="ellipsis" @click="showShare = true"/>
    </span>
  </van-nav-bar>
  <!-- /导航栏 -->

  <div class="main-wrap">
    <!-- 加载中 -->
    <div class="loading-wrap" v-if="loading">
      <van-loading color="#3296fa" vertical>加载中</van-loading>
    </div>
    <!-- /加载中 -->

    <!-- 加载完成-文章详情 -->
    <div class="article-detail" v-else-if="news.title">
      <!-- 文章标题 -->
      <h1 class="article-title">{{news.title}}</h1>
      <div class="publish-date">
        {{timestamp2fromNow(news.pubdate)}}
        <span class="split-line">|</span>
        <span class="read-count">{{news.read_count}}&nbsp;阅读</span>
        <span class="split-line">|</span>
        <span class="comment-count">{{news.comm_count}}&nbsp;评论</span>
      </div>
      <!-- /文章标题 -->

      <!-- 用户信息 -->
      <van-cell class="user-info" center :border="false">
        <van-image class="avatar" slot="icon" round fit="cover" :src="news.aut_photo"/>
        <div slot="title" class="user-name">{{news.aut_name}}</div>

        <FollowUser class="follow-btn" :userId="news.aut_id" v-model="news.is_followed"></FollowUser>
      </van-cell>
      <!-- /用户信息 -->

      <!-- 文章内容 -->
      <div
        class="article-content markdown-body"
        @scroll="onScroll"
        v-html="news.content"
        ref="news.content"
        v-highlight
      ></div>
      <div class="footer">发布文章时间: {{timestamp2fromNow(news.pubdate)}}</div>
      <!-- 文章评论 -->
      <van-sticky :offset-top="46">
        <van-cell value>
          <template slot="title">
            <span class="custom-title">全部评论&nbsp;({{news.comm_count}})</span>
          </template>
          <template #default>{{news.like_count}} 点赞</template>
        </van-cell>
      </van-sticky>

      <CommentList
        :list="commentList"
        v-if="news.comm_count"
        :source="news.art_id"
        @onload-success="totaiCommentCount = $event"
        :article-id="news.art_id"
      ></CommentList>
      <van-empty v-else description="还没有人评论哦"/>
      <!-- 底部区域 -->
      <div class="article-bottom">
        <van-button
          class="comment-btn"
          type="default"
          round
          size="small"
          @click="isPostShow = true"
        >写评论</van-button>
        <van-icon name="comment-o" :badge="totaiCommentCount" color="#777"/>
        <!-- <van-icon color="#777" name="star-o"/> -->
        <CollectArticle v-model="news.is_collected" :article-id="news.art_id"></CollectArticle>
        <!-- <van-icon color="#777" name="good-job-o"/> -->
        <likeArticle v-model="news.attitude" :article-id="news.art_id"/>
        <van-icon name="share" color="#777777" @click="showShare = true"></van-icon>
      </div>
      <!-- /底部区域 -->
    </div>
    <!-- /加载完成-文章详情 -->

    <!-- 加载失败：404 -->
    <div class="error-wrap" v-else-if="errStatus === 404">
      <van-icon name="failure"/>
      <p class="text">该资源不存在或已删除！</p>
    </div>
    <!-- /加载失败：404 -->

    <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
    <div class="error-wrap" v-else>
      <van-icon name="failure"/>
      <p class="text">内容加载失败！</p>
      <van-button class="retry-btn" @click="loadArticle">点击重试</van-button>
    </div>
    <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
  </div>
  <!-- 分享弹窗 -->
  <van-share-sheet v-model="showShare" title="立即分享给好友" :options="options" @select="onSelect"/>
  <!-- 评论弹窗 -->
  <van-popup v-model="isPostShow" position="bottom">
    <comment-post :target="news.art_id" @post-success="onPostSuccess"/>
  </van-popup>
</div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { follow, noFollow } from "@/api/article.js";
import { getNews } from "@/views/home/store";
import moment from "moment";
import { ImagePreview } from "vant";
import FollowUser from "@/components/follow-user";
import CollectArticle from "@/components/collect-article";
import likeArticle from "@/components/like-article";
import CommentList from "@/views/article/components/comment-list";
import CommentPost from "./components/comment-post";
import "vue-hljs/dist/style.css";
export default {
  name: "ArticleIndex",
  components: {},
  props: {
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      loading: true,
      errStatus: 0,
      followLoading: false, // 按钮加载
      showShare: false,
      commentList: [], // 评论列表
      isPostShow: false,
      totaiCommentCount: 0,
      options: [
        [
          { name: "微信", icon: "wechat" },
          { name: "朋友圈", icon: "wechat-moments" },
          { name: "微博", icon: "weibo" },
          { name: "QQ", icon: "qq" }
        ],
        [
          { name: "复制链接", icon: "link" },
          { name: "分享海报", icon: "poster" },
          { name: "二维码", icon: "qrcode" },
          { name: "小程序码", icon: "weapp-qrcode" }
        ]
      ],
      authVisible: true
    };
  },
  computed: {
    ...mapState("articles", ["news"])
  },
  watch: {},
  created() {
    this.loadArtcileInfo();
  },
  mounted() {},
  methods: {
    ...mapActions("articles", ["getNews"]),
    onClickLeft() {
      this.$router.back();
    },
    async loadArtcileInfo() {
      this.loading = true;
      try {
        const { res } = await this.getNews(this.articleId);
        this.previewImage();
        this.loading = false;
      } catch (err) {
        if (err.response && err.response.status === 404) {
          this.errStatus = 404;
        }
        // this.$toast("获取失败");
        this.loading = false;
      }
    },
    timestamp2fromNow(timestamp) {
      return moment(timestamp).format("YYYY年MM月DD日");
    },
    previewImage() {
      // 得到所有的 img 节点
      const articleContent = this.$refs["news-content"];
      const imgs = articleContent.querySelectorAll("img");

      // 获取所有 img 地址
      const images = [];
      imgs.forEach((img, index) => {
        images.push(img.src);

        // 给每个 img 注册点击事件，在处理函数中调用预览
        img.onclick = () => {
          ImagePreview({
            // 预览的图片地址数组
            images,
            // 起始位置，从 0 开始
            startPosition: index
          });
        };
      });
    },
    // async onFollow() {
    //   try {
    //     this.followLoading = true
    //     if (this.news.is_followed) {
    //       const { data } = await follow(this.news.aut_id);
    //       this.news.is_followed = false;
    //     } else {
    //       const { data } = await noFollow(this.news.aut_id);
    //       this.news.is_followed = true;
    //       // console.log(data);
    //     }
    //   } catch (err) {
    //     if (err.response && err.response.status === 400) {
    //       return this.$toast.fail("你不能关注自己");
    //     }
    //     this.$toast.fail("操作失败");
    //   }
    //   this.followLoading = false
    // },
    onSelect(option) {
      Toast(option.name);
      this.showShare = false;
    },
    onScroll(e) {
      if (e.target.scrollTop > 100) {
        console.log(111);
        this.authVisible = true;
      } else {
        this.authVisible = false;
      }
    },
    Back() {
      this.$router.back();
    },
    onFollow() {
      // try {
      //   if (news.isFollowed) {
      //     await follow(news.aut_id);
      //       news.isFollowed = false;
      //   } else {
      //     await noFollow(news.aut_id);
      //       news.isFollowed = true;
      //     // console.log(data);
      //   }
      //   this.$toast.success(news.isFollowed ? "关注成功" : "取消关注");
      // } catch (err) {
      //   if (err.response && err.response.status === 400) {
      //     return this.$toast.fail("你不能关注自己");
      //   }
      //   this.$toast.fail("操作失败");
      // }
    },
    onPostSuccess(data) {
      // 关闭弹出层
      this.isPostShow = false;
      // 将发布内容显示到列表顶部
      this.commentList.unshift(data.new_obj);
    },
    onReplyClick (comment) {
      console.log(comment);
      
    }
  },
  components: {
    FollowUser,
    CollectArticle,
    likeArticle,
    CommentList,
    CommentPost
  }
};
</script>

<style scoped lang="less">
@import "./github-markdown.css";
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 102px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }
    .publish-date {
      margin-top: -20px;
      margin-left: 50px;
      width: 450px;
      font-size: 25px;
      color: #b7b7b7;
      span {
        margin-left: 6px;
      }
    }

    .user-info {
      padding: 0 32px;
      margin-top: 30px;
      .avatar {
        width: 90px;
        height: 90px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        margin-left: 10px;
        font-size: 36px;
        color: #3a3a3a;
      }

      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      height: auto;
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
    .footer {
      padding-right: 20px;
      font-size: 25px;
      text-align: right;
      color: #a5a6ab;
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    /deep/ .van-icon {
      font-size: 40px;
      color: rgb(196, 129, 129);
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
::v-deep .van-nav-bar__left {
  width: 90%;
  height: 100%;
  top: 0px;
  left: 0px;
  .van-icon {
    top: 0px;
    left: -20px;
  }
  .autname {
    margin-left: 10px;
    color: #fff;
  }
  .van-button {
    position: absolute;
    top: 15px;
    left: 320px;
    font-size: 15px;
    border: 0;
  }
}
::v-deep .van-nav-bar__title {
  font-size: 16px;
  margin: 0 150px;
}
::v-deep .publish-wrap {
  .van-icon {
    color: red;
    font-size: 50px;
  }
  .van-cell__title {
    font-size: 30px;
    margin-left: 100px;
    text-align: right;
  }
  .van-cell__value {
    font-size: 30px;
    color: red;
  }
}
</style>